package org.flowers.unbeaten.generator;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.flowers.unbeaten.generator.base.AbstractGenerator;
import org.flowers.unbeaten.generator.configuration.GeneratorConfiguration;
import org.flowers.unbeaten.generator.entity.GeneratorEntity;
import org.flowers.unbeaten.util.FileCompressUtils;
import org.flowers.unbeaten.util.FileUtils;

import java.io.File;
import java.io.FileOutputStream;

/**
 * @description 代码生成器
 * @author RyanWang
 * @date 2021-08-13 15:56:52
 * @version 1.0
 */
@Slf4j
@Data
public class Generator extends AbstractGenerator {

    /**
     * 构建一个Generator对象
     * @param generatorEntity
     * @return
     */
    public static Generator builder(GeneratorEntity generatorEntity) {
        Generator generator = new Generator();
        generator.init(generatorEntity);
        return generator;
    }

    @Override
    public String execute() throws Exception {
        // 设置生成临时路径
        String tmpdir = System.getProperty("java.io.tmpdir") + "fastCoding." + IdWorker.getIdStr();
        generatorEntity.setTempPath(tmpdir);
        // 配置MybatisPlus,并执行生成
        AutoGenerator autoGenerator = this.setMybatisPlusConfig(generatorEntity);
        autoGenerator.execute();
        log.info("代码生成完毕! 正在努力压缩文件中...");
        // 生成完成进行压缩处理
        if(FileUtils.validateFileIsExists(tmpdir)) {
            FileOutputStream fos = new FileOutputStream(new File(tmpdir + "code.zip"));
            FileCompressUtils.toZip(tmpdir,"flowers_unbeaten_" + generatorEntity.getModuleName(),fos,true);
        }
        return tmpdir;
    }

    /**
     * Mybatis Plus 配置
     * @param generatorEntity
     * @return
     */
    private AutoGenerator setMybatisPlusConfig(GeneratorEntity generatorEntity) {
        AutoGenerator generator = new AutoGenerator();
        // MybatisPlus 配置
        GeneratorConfiguration config = new GeneratorConfiguration().initConfiguration(generatorEntity);
        generator.setGlobalConfig(config.initGlobalConfig());
        generator.setDataSource(config.initDataSourceConfig());
        generator.setStrategy(config.initStrategyConfig());
        generator.setPackageInfo(config.initPackageConfig());
        generator.setTemplate(config.initTemplateConfig());
        generator.setTemplateEngine(config.initTemplateEngine());
        return generator;
    }
}
